﻿using ChuanYe.Core.Utils;
using ChuanYe.CountyFireManagement.BLL;
using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using ChuanYe.CountyFireManagement.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace ChuanYe.CountyFireManagement.Api
{


    public class 项目经理与移动端开发者吃屎的故事
    {

        /// <summary>
        /// MQTT Client
        /// </summary>
        public static MQClient client = null;

        /// <summary>
        /// 成员变量
        /// </summary>
        private static string fireDispose = "FireDispose/Operation/Mobile/GPS/#";

        /// <summary>
        /// 瞎写的没啥用
        /// </summary>
        private static readonly object writeLock = new object();

        /// <summary>
        /// 先放一下
        /// </summary>
        private static  List<狗屎的实体> ALL_ARRAY = new List<狗屎的实体>();
        public static void 开讲啦() 
        {
            string[] topic_split = new string[] { fireDispose };
            client = new MQClient("ChuanYe_这TM是我声明了一个吃屎对象");
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    client.TryConnect();
                    Thread.Sleep(2000);
                    if (client.client != null && (bool)client.client.IsConnected == true)
                    {
                        client.client.Subscribe(topic_split, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
                        client.client.MqttMsgPublishReceived += 订阅一坨狗屎;
                        break;
                    }
                }
                正在吃屎();
            });

        }
        private static void 订阅一坨狗屎(object sender, MqttMsgPublishEventArgs e)
        {
            var json = Encoding.UTF8.GetString(e.Message);
            try
            {
                var data = Newtonsoft.Json.JsonConvert.DeserializeObject<狗屎的实体>(json);
                ALL_ARRAY.Add(data);
            }
            catch (Exception ex)
            {
              
            }
        }

        private static void 正在吃屎()
        {
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (client.client == null || (bool)client.client.IsConnected == false)
                    {
                        client.TryConnect();
                        if (client.client != null && (bool)client.client.IsConnected == true)
                        {
                            client.client.MqttMsgPublishReceived += 订阅一坨狗屎;
                        }
                        Thread.Sleep(2000);
                        continue;
                    }
                    List<狗屎的实体> ADD_ARRAY = new List<狗屎的实体>();
                    lock (writeLock)
                    {
                        ADD_ARRAY.AddRange(ALL_ARRAY.ToList());
                        ALL_ARRAY.Clear();
                    }
                    if (ADD_ARRAY.Count != 0)
                    {
                        lock (writeLock)
                        {
                            foreach (var item in ADD_ARRAY)
                            {
                                GpsDeviceBLL.Instance.Add(new Gpsdevice()
                                {
                                    CreateTime = DateTime.Now,
                                    GpsDeviceNo = item.IMEI,
                                    GpsDeviceName = DateTime.Now.ToString("yyyyMMddHHmmsss"),
                                });

                                var existGpsDevcie = GpsDeviceBLL.Instance.Get(item.IMEI);
                                var existGpsDeviceConfig = GpsDeviceConfigBLL.Instance.Get((int)GpsBindTypeEnum.User, item.UserId);
                                Gpsdevicerecord info = new Gpsdevicerecord();
                                if (existGpsDeviceConfig == null)
                                {
                                    var existGpsDeviceConfig2 = GpsDeviceConfigBLL.Instance.Get(item.IMEI);
                                    if (existGpsDeviceConfig2 == null)
                                    {
                                        GpsDeviceConfigBLL.Instance.Add(new Gpsdeviceconfig()
                                        {
                                            CreateTime = DateTime.Now,
                                            BindId = item.UserId,
                                            BindType = (int)GpsBindTypeEnum.User,
                                            GpsDeviceId = existGpsDevcie.GpsDeviceId,
                                        });
                                    }
                                    else
                                    {
                                        //编辑
                                        GpsDeviceConfigBLL.Instance.Update(new Gpsdeviceconfig() {
                                            CreateTime = DateTime.Now,
                                            BindId = item.UserId,
                                            BindType = (int)GpsBindTypeEnum.User,
                                            GpsDeviceId=existGpsDevcie.GpsDeviceId,
                                            ConfigId= existGpsDeviceConfig2.ConfigId,
                                        });
                                    }
                                }
                                info.GpsDeviceRecordGuid = System.Guid.NewGuid().ToString();
                                info.GpsDeviceId = existGpsDevcie.GpsDeviceId;
                                info.Latitude = item.Latitude;
                                info.Longitude = item.Latitude;
                                info.Speed = item.Speed;
                                info.RecordTime = StampToDateTime(item.DataTime);
                                info.Accuracy = item.Accuracy;
                                info.Altitude = item.Altitude;
                                info.Bearing = item.Bearing;
                                info.CreateTime = DateTime.Now;
                                GpsDeviceRecordBLL.Instance.AddList(new List<Gpsdevicerecord>() { info });
                            }

                            ADD_ARRAY.Clear();
                        }
                        Thread.Sleep(1000);
                    }

                }
            });
        }

        private static DateTime StampToDateTime(long stamp)
        {
            try
            {
                DateTime StartDateTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));
                if (stamp.ToString().Length == 10) StartDateTime.AddSeconds(stamp);
                return StartDateTime.AddMilliseconds(stamp);
            }
            catch (Exception)
            {
                return DateTime.Now;
            }
        }

        class 狗屎的实体
        {
            /// <summary>
            /// 必填 流水号
            /// </summary>
            public string GpsDeviceRecordGuid { get; set; } = System.Guid.NewGuid().ToString();

            /// <summary>
            /// 用户编号
            /// </summary>
            public int UserId { get; set; }

            /// <summary>
            /// 用户编号
            /// </summary>
            public string IMEI { get; set; }

            /// <summary>
            /// 纬度
            /// </summary>
            public string Latitude { get; set; }

            /// <summary>
            /// 经度
            /// </summary>
            public string Longitude { get; set; }

            /// <summary>
            /// 高度
            /// </summary>
            public string Altitude { get; set; }

            /// <summary>
            /// 精度
            /// </summary>
            public string Accuracy { get; set; }

            /// <summary>
            /// 速度
            /// </summary>
            public string Speed { get; set; }

            /// <summary>
            /// 方位
            /// </summary>
            public string Bearing { get; set; }

            /// <summary>
            /// 这是个什么玩意
            /// </summary>
            public long DataTime { get; set; }
        }
    }

  
     
}
